﻿using Google.Protobuf.WellKnownTypes;
using Logproto;
using Microsoft.Extensions.Logging;

namespace LokiProvider;

internal class LokiLogger : ILogger
{
    private LokiLoggerProvider _parent;
    private string _category;
    private string _app;
    internal LokiLogger(LokiLoggerProvider parent, string app, string category)
    {
        _parent = parent;
        _app = app;
        _category = category;
    }

    public IDisposable? BeginScope<TState>(TState state) where TState : notnull
    {
        return null;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        return logLevel != LogLevel.None;
    }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
        Func<TState, Exception?, string> formatter)
    {
        var msg = formatter(state, exception);
        if (exception != null)
        {
            msg = msg + "\n" + exception;
        }
        var stream = new StreamAdapter
        {
            Labels = $"{{app=\"{_app}\",category=\"{_category}\",level=\"{logLevel}\"}}",
        };
        stream.Entries.Add(new EntryAdapter { Timestamp = Timestamp.FromDateTime(DateTime.UtcNow), Line = msg });
        stream.Hash = (ulong)stream.GetHashCode();
        _parent.Add(stream);
    }
}